﻿
//获取图片exif的工具
var __exif = {};
__exif.base64ToArrayBuffer = function (base64, contentType) {
    contentType = contentType || base64.match(/^data\:([^\;]+)\;base64,/mi)[1] || ''; // e.g. 'data:image/jpeg;base64,...' => 'image/jpeg'
    base64 = base64.replace(/^data\:([^\;]+)\;base64,/gmi, '');
    var binary = atob(base64);
    var len = binary.length;
    var buffer = new ArrayBuffer(len);
    var view = new Uint8Array(buffer);
    for (var i = 0; i < len; i++) {
        view[i] = binary.charCodeAt(i);
    }
    return buffer;
}
__exif.getExifInfo = function (fileBase64) {
    var buffer = __exif.base64ToArrayBuffer(fileBase64);
    var dataView = new DataView(buffer);
    if ((dataView.getUint8(0) != 0xFF) || (dataView.getUint8(1) != 0xD8)) {
        return { success: false, message: 'not a valid jpeg' };
    }

    var offset = 2,
        length = dataView.byteLength,
        marker;

    while (offset < length) {
        if (dataView.getUint8(offset) != 0xFF) {
            return { success: false, message: 'not a valid marker, something is wrong' };
        }

        marker = dataView.getUint8(offset + 1);
        if (marker == 0xE1) {
            //console.log("Found 0xFFE1 marker");
            return __exif.readEXIFData(dataView, offset + 4);
        } else {
            offset += 2 + dataView.getUint16(offset + 2);
        }
    }

    return { success: false, message: 'not find 0xFFE1 for EXIF data' };
}
__exif.readEXIFData = function (dataView, start) {
    //console.log(dataView.getUint32(start).toString(16));
    if (dataView.getUint32(start) != 0x45786966) {
        return { success: false, message: 'Not valid EXIF data' };
    }
    var bigEnd,
        tags, tag,
        exifData, gpsData,
        tiffOffset = start + 6;

    // test for TIFF validity and endianness
    if (dataView.getUint16(tiffOffset) == 0x4949) {
        bigEnd = false;
    } else if (dataView.getUint16(tiffOffset) == 0x4D4D) {
        bigEnd = true;
    } else {
        return { success: false, message: 'Not valid TIFF data! (no 0x4949 or 0x4D4D)' };
    }
    if (dataView.getUint16(tiffOffset + 2, !bigEnd) != 0x002A) {
        return { success: false, message: 'Not valid TIFF data! (no 0x002A)' };
    }

    var firstIFDOffset = dataView.getUint32(tiffOffset + 4, !bigEnd);
    if (firstIFDOffset < 0x00000008) {
        return { success: false, message: 'Not valid TIFF data! (First offset less than 8)' };
    }

    var tagCount = dataView.getUint16(tiffOffset + 8, !bigEnd);
    //console.log('tagCount='+tagCount);
    for (var i = 0; i < tagCount; i++) {
        var tagOffset = tiffOffset + 8 + 2 + (i * 12);
        var tagCode = dataView.getUint16(tagOffset, !bigEnd);
        //console.log('tagCode='+tagCode.toString(16));
        if (tagCode == 0x0112) {
            //0112 0003 0000 0001 0006 0000
            var Orientation = dataView.getUint16(tagOffset + 8, !bigEnd);
            //console.log('Orientation='+Orientation.toString(16));
            return {
                success: true,
                message: 'OK',
                data: {
                    Orientation: Orientation
                }
            };
        }
    }
    return { success: false, message: 'Not Orientation of TIFF data! (no 0x0112)' };
}

//压缩图片
function zoomImage(file, formData, maxSize, callback, supportWebp) {
    return new Promise((resolve, reject) => {
        var reader = new FileReader();
        maxSize = maxSize || 1920;
        reader.onload = function () {
            //var exif = __exif.getExifInfo(reader.result);
            var img = new Image();
            img.onload = function () {
                var w = img.width;
                var h = img.height;
                if (w > maxSize || h > maxSize) {
                    //计算缩放后size
                    if (w > h) {
                        h = h * maxSize / w;
                        w = maxSize;
                    }
                    else {
                        w = w * maxSize / h;
                        h = maxSize;
                    }
                }
                //无论是否缩放都绘制一次，这样可以统计转换成jpg格式，
                var canvas = document.createElement('canvas');
                var ctx = canvas.getContext('2d');
                canvas.width = w;
                canvas.height = h;


                ctx.drawImage(img, 0, 0, w, h);

                let fn = file.name.substring(0, file.name.lastIndexOf("."));
                fn = fn + (supportWebp ? ".webp" : ".jpg");
                canvas.toBlob(function (blob) {
                    formData.append('file', blob, fn);
                    if(callback){
                        callback(formData);
                    }
                    resolve(formData);
                }, supportWebp ? "image/webp" : "image/jpeg", 0.85);
            }
            img.src = reader.result;
        }
        reader.readAsDataURL(file);
    });
}

export default zoomImage;